package com.authine.cloudpivot.ext.controller.trainingData;

import cn.hutool.core.lang.Assert;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.*;

import static java.util.Objects.isNull;

/**
 * 培训周知卡 实施
 **/
@RestController
@RequestMapping("/public/trainingConduct")
@Slf4j
public class TrainingConductController extends BaseController {


    @Autowired
    CloudSqlService sqlService;

    /**
     * 培训周知卡 实施  审批流完成后 调用存储过程
     */
    @RequestMapping("finish")
    public void finish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.TrainingConduct, bizId);

        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("trainingConductDetail");

//        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人

//        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {
            try {
                //调用存储过程
                callProcess(map);
            } catch (Exception e) {
                log.info("培训周知卡实施调用存储过程失败: {},子表id={}", bizId, map.get("id"));
                log.info(e.getMessage(), e);
            }

        }
    }


    /**
     * 调用存储过程
     * -----员工培训周知卡   实施
     * exec    SyncTrainImplement
     * FID       nvarchar(100),	     ----员工培训基础FID
     * CompleteDate  nvarchar(50),	     ----完成时间
     * Result      nvarchar(50),	     ----学习结果     1 -- A    2 -- B   3 -- C
     * @LearnTime		nvarchar(50),	----学习时长
     * WorkDesc	   nvarchar(200),    ----工作说明
     * RelateFile	   nvarchar(200)     ----相关档案
     */
    private void callProcess(Map<String, Object> map) {


        log.info("入参map={}", map);

        //调用存储过程
        Map<String, Object> trainData = (Map<String, Object>) map.get("trainDataFid");
        String fid = MapUtils.getString(trainData, "id", "");
        Date complete = (Date) map.get("completeDate");

//        LocalDateTime complete = (LocalDateTime) map.get("completeDate");
//        String planDate =  ObjectUtils.isEmpty(planDateTemp) ? "" : planDateTemp.toLocalDate().toString();



        String completeDate = "";
        if (complete != null) {
            completeDate = DateFormatUtils.format(complete, "yyyy-MM-dd");
        }

        String studyresultStr = MapUtils.getString(map, "studyresult", "");
        Integer studyresult = null;
        if (studyresultStr.equals("A")) {
            studyresult = 1;
        } else if (studyresultStr.equals("B")) {
            studyresult = 2;
        } else if (studyresultStr.equals("C")) {
            studyresult = 3;
        }


        double NumLearnTime = MapUtils.getDouble(map, "NumLearnTime", (double) 0);


//        String txtLearnTime = MapUtils.getString(map, "txtLearnTime", "");
        String workDesc = MapUtils.getString(map, "workDesc", "");
//        String workDescReplace = workDesc.replace("\\", "\\\\");

        String relateFile = MapUtils.getString(map, "relateFile", "");
//        String relateFileReplace = relateFile.replace("\\", "\\\\");

//        Assert.isFalse(StringUtils.isEmpty(fid), "{}不能为空", "fid");
//        Assert.isFalse(StringUtils.isEmpty(completeDate), "{}不能为空", "completeDate");
//        Assert.isFalse(studyresult == null, "{}不能为空", "studyresult");
//        Assert.isFalse(StringUtils.isEmpty(workDesc), "{}不能为空", "workDesc");
//        Assert.isFalse(StringUtils.isEmpty(relateFile), "{}不能为空", "relateFile");
        log.info("\n==========存储过程参数{},{},{},{},{}", fid, completeDate, studyresult, workDesc, relateFile);
        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncTrainImplement '%s','%s','%s',%s,'%s','%s'",
                fid, completeDate, studyresult, NumLearnTime,workDesc, relateFile);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============存储过程执行完成");

    }


    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity8";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append(" ").append(user.getName()).toString();
    }


    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map data) {

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.funOneLevelBase);
        String oneLevelCode = (String) data.get("oneLevelCode");
        String funCode = (String) data.get("funCode");

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where funCode='").append(funCode).append("' and oneLevelCode='")
                .append(oneLevelCode).append("';");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     * 转换成  基础表-总公司档案 的数据
     *
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String, Object> fileInfoBaseMap(Map<String, Object> map, String auditDate, String auditer) {
        Map<String, Object> data = new HashMap<>();

        //审批时间
        data.put("auditDate", map.get("auditDate"));
        //审批人
        data.put("auditer", map.get("auditer"));
        //职能代码隐藏
        data.put("funCode", map.get("funCode"));
        //职能总责部门代码隐藏
        data.put("funDutyDeptCode", map.get("funDutyDeptCode"));
        //职能总责部门
        data.put("funDutyDeptName", map.get("funDutyDeptName"));
        //职能
        data.put("funName", map.get("funName"));
        //一级代码
        data.put("oneLevelCode", map.get("oneLevelCode"));
        //一级职责
        data.put("oneLevelDuty", map.get("oneLevelDuty"));
        //职能代码
        data.put("relevFun", map.get("relevFun"));
        //职能总责部门代码
        data.put("relevFunDutyDept", map.get("relevFunDutyDept"));

        //审批时间
        data.put("auditDate", auditDate);
        //审批人
        data.put("auditer", auditer);

        return data;
    }
}
